<?

class QAjaxResult{
    
    const TYPE_ERROR = 'error';
    const TYPE_SUCCESS = 'success';
    
    private $data = array(
        'type' => 'error',
        'message' => 'unknow',
        'data' => array()
    );
    
    function __construct($type='error', $message='unknow', $data=array()){
        $this->set($type, $message, $data);
    }
    
    function set($type='error', $message='unknow', $data=array()){
        if($type != 'error') $this->setType($type);
        if($message != 'unknow') $this->setMessage($message);
        if(!empty($data)) $this->setData($data);
        return $this;
    }
    
    function setType($type){ $this->data['type'] = $type; return $this; }
    function setMessage($message){ $this->data['message'] = $message; return $this; }
    function setData($data){ $this->data['data'] = $data; return $this; }
    
    function getType(){ return $this->data['type']; }
    function getMessage(){ return $this->data['message']; }
    function getData(){ return $this->data['data']; }
    
    function result(){
        return json_encode($this->data);
    }
    
    function __toString(){
        return $this->result();
    }
    
    function multiResult($backurl=false){
        $backurl = !$backurl ? $_SERVER['HTTP_REFERER'] : $backurl;
        if(CHttpRequest::getIsAjaxRequest()){
            echo $this;
        }else{
            if($this->getType() == self::TYPE_ERROR){
                Yii::app()->user->setFlash(FL_ERROR, $this->getMessage());
            }else{
                Yii::app()->user->setFlash(FL_SUCCESS, $this->getMessage());
            }
            Yii::app()->GetController->redirect($backurl);
        }
    }
    
}
